import axios from "axios"; // 引入axios
import Cookies from "js-cookie";
import DonMessage from "@/common/js/message";
import { Notification } from "element-ui";
let { NODE_ENV } = process.env;
import { ssoDomain, appId } from "@/utils/config";
import router from "@/router";

//连接mock连接
const http = axios.create({
  // baseURL: '/',
  timeout: 100000,
  responseType: "json",
  withCredentials: true,
  headers: {
    httponly: true,
    secure: true,
    auth: "tas@waterdrop",
  },
});
/**
 * mooncell接口 需要传递secPass参数
 * @param {string} :接口地址
 * @return:{object}: {secPass:cookie中的sec_pass}
 */
function getSecPass(url) {
  let moomcell = ["moonApi", "moonApi-ue", "moonApi-de"];
  //如果类似http://pre.mooncell.intra.xiaojukeji.com/moonApi这样的接口 就需要传sec_pass参数
  if (/^http(s)?:\/\/.*/i.test(url)) {
    let pr = url.split("/")[3];
    if (moomcell.includes(pr)) {
      return {
        username: Cookies.get("_sso_username"),
        secPass:
          Cookies.get("sec_pass") ||
          "ACO37YMR2MU6QMRNLJZCAPOPMX4RLUW7AB5GE25HD6QTWYZMKVWL7XU337SXJV622632JVUDN73E4H7UE7XD4M5ZAGRGP4YT2M4DLD4MHKYF7CERAEHMNSD4KUZYSTD5GJGB7AYPTJ4GFGVPCGYTHU25NOSKAJJB6KNNKMK5OXYV52XODCLGOJYBGCPWDUD7WN4R6MWV3A4UA",
      };
    }
  }
  return {}; //
}
function removeLoading() {
  let loadingDom = document.querySelector(".el-loading-mask.loading");
  loadingDom && loadingDom.remove();
  //按钮下的loading
  let loadingBtn = document.querySelectorAll(".el-button.is-loading");
  loadingBtn?.forEach((item) => {
    item.classList.remove("is-loading"); //移除class样式
    item.removeAttribute("disabled"); //移除按钮禁用
    let loadingDom = item.children[0];
    if (loadingDom.className == "el-icon-loading") {
      loadingDom.remove();
    }
  });
}
/**
 * get方法，对应get请求
 * @param {String} url [请求的url地址]
 * @param {Object} params [请求时携带的参数]
 */
export function get(url, params, headers) {
  return new Promise((resolve, reject) => {
    http
      .get(url, { params: { ...params, ...getSecPass(url), ...headers } })
      .then((res) => {
        console.log("[ http ] >", res.data);
        resolve(res.data);
      })
      .catch((err) => {
        removeLoading();
        reject(err.data);
      });
  });
}
/**
 * post方法，对应post请求
 * @param {String} url [请求的url地址]
 * @param {Object} params [请求时携带的参数]
 */
export function post(url, params) {
  return new Promise((resolve, reject) => {
    //由于后台有数据权限，必须要提供一个正确的账户
    http
      .post(url, params, { params: getSecPass(url) })
      .then((res) => {
        resolve(res.data);
      })
      .catch((err) => {
        removeLoading();
        reject(err.data);
      });
  });
}
/**
 * @函数功能:请求拦截器 添加请求头
 * @参数输入:
 * @函数返回:
 */
http.interceptors.request.use(
  (config) => {
    if (NODE_ENV === "development" || NODE_ENV === "test") {
      config.headers["loginUser"] = "test";
    }
    return config;
  },
  (err) => {
    console.log(err);
    return Promise.reject(err);
  },
);

/**
 * @函数功能:拦截器
 * @参数输入:
 * @函数返回:
 */
http.interceptors.response.use(
  (data) => {
    //未知情况
    if (!data.data) {
      new DonMessage().warning({
        message: JSON.stringify(data),
      });
      return Promise.reject(err);
    }
    if (data.data.code === "403") {
      router.push("/403");
      return Promise.reject(err);
    }
    if (data.data.code === "302") {
      let now_url = encodeURIComponent(window.location.href);
      let url = `${ssoDomain[NODE_ENV]}/auth/sso/login?app_id=${appId[NODE_ENV]}&jumpto=${now_url}&version=1.0`;
      location.href = url;
      return Promise.reject(err);
    }
    if (data.data.code === "1") {
      Notification({
        title: "操作异常",
        message: data.data.msg,
        position: "top-right",
        duration: 8000,
      });
      return Promise.reject(err);
    }
    //响应出现问题
    let resUrl = data.request.responseURL;
    if (data.data.code != "0" && !resUrl.includes("rest/process-instances/forecast")) {
      new DonMessage().error({
        message: data.data.msg,
      });
      return Promise.reject(err);
    }
    return data;
  },
  (err) => {
    if (err.response.status === 302) {
      let now_url = encodeURIComponent(window.location.href);
      let url = `${ssoDomain[NODE_ENV]}/auth/sso/login?app_id=${appId[NODE_ENV]}&jumpto=${now_url}&version=1.0`;
      location.href = url;
      return;
    } else if (err.response.status === 403) {
      router.push("/403");
      return Promise.reject(err);
    }
    new DonMessage().error({
      message: `程序出错了，请联系管理员：${err.response.statusText}（${err.response.status}）`,
    });
    return Promise.reject(err);
  },
);
